package service

import (
	"crypto/md5"
	"fmt"
	"gitee.com/video_web/cmd/user/dal/db"
	"gitee.com/video_web/kitex_gen/user"
	"gitee.com/video_web/pkg/errno"
	"github.com/gofrs/uuid"
	"io"
	"strings"
)

// CreateUser create user info.
func (s *WriteUserService) CreateUser(req *user.CreateUserRequest) error {
	users, err := db.QueryUser(s.ctx, req.Username)
	if err != nil {
		return err
	}
	if len(users) != 0 {
		return errno.UserAlreadyExistErr
	}

	h := md5.New()
	if _, err = io.WriteString(h, req.Password); err != nil {
		return err
	}
	password := fmt.Sprintf("%x", h.Sum(nil))

	u, err := uuid.NewV7()
	if err != nil {
		fmt.Printf("Failed to generate UUID: %v", err)
		return err
	}
	uuidStr := strings.ReplaceAll(u.String(), "-", "")

	return db.CreateUser(s.ctx, []*db.User{{
		ID:       uuidStr,
		Username: req.Username,
		Password: password,
	}})
}
